package cn.com.tianpeidong.restaurantadmin.project.admin.user.service.impl;

import cn.com.tianpeidong.restaurantadmin.common.exception.BusinessException;
import cn.com.tianpeidong.restaurantadmin.common.util.msg.MessageUtils;
import cn.com.tianpeidong.restaurantadmin.common.util.security.ShiroUtils;
import cn.com.tianpeidong.restaurantadmin.project.admin.role.entity.Role;
import cn.com.tianpeidong.restaurantadmin.project.admin.role.mapper.RoleMapper;
import cn.com.tianpeidong.restaurantadmin.project.admin.user.entity.UserInfo;
import cn.com.tianpeidong.restaurantadmin.project.admin.user.entity.UserRole;
import cn.com.tianpeidong.restaurantadmin.project.admin.user.mapper.UserInfoMapper;
import cn.com.tianpeidong.restaurantadmin.project.admin.user.service.IUserInfoService;
import cn.com.tianpeidong.restaurantadmin.project.admin.user.vo.ModifyPasswd;
import cn.com.tianpeidong.restaurantadmin.project.admin.user.vo.UserVO;
import lombok.NonNull;
import org.apache.shiro.crypto.hash.Md5Hash;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

import static cn.com.tianpeidong.restaurantadmin.common.web.constant.ProjectConstant.*;

/**
 * @author tianpeidong
 * @version 创建时间: 19-4-7 下午5:40
 */
@Service
public class UserInfoServiceImpl implements IUserInfoService {

    @Autowired
    private UserInfoMapper userInfoMapper;

    @Autowired
    private RoleMapper roleMapper;

    @Override
    public List<UserVO> listUser(UserVO userVO) {
        return userInfoMapper.listUser(userVO);
    }

    @Override
    public UserInfo add(@NonNull UserVO userVO) {
        String userName = userVO.getUserName();

        Long roleId = userVO.getRoleId();
        if (roleId.equals(DEFAULT_ADMIN_ROLE_ID)) {
            throw new BusinessException(MessageUtils.message("user.role.illegal"));
        }
        Role role = roleMapper.getById(roleId);
        if (role == null) {
            throw new BusinessException(MessageUtils.message("user.role.illegal"));
        }
        String salt = getRandomSalt();
        UserInfo userInfo = new UserInfo();
        userInfo.setSalt(salt);
        userInfo.setPassword(new Md5Hash(userName + DEFAULT_PASSWORD + salt).toHex());
        userInfo.setUserName(userVO.getUserName());
        int res =  userInfoMapper.insert(userInfo);
        if (res > 0) {
            UserRole userRole = new UserRole();
            userRole.setRoleId(roleId);
            userRole.setUserId(userVO.getId());
            userInfoMapper.insertUserRole(userRole);
        }
        return userInfo;
    }

    @Override
    public void delete(@NonNull Long userId) {
        if (userId.equals(DEFAULT_ADMIN_ID)) {
            throw new BusinessException(MessageUtils.message("operate.not.allowed"));
        }
        userInfoMapper.deleteUser(userId);
    }

    @Override
    public UserInfo resetPasswd(@NonNull Long userId) {
        UserInfo userInfo = userInfoMapper.getById(userId);
        if (userInfo == null) {
            throw new BusinessException(MessageUtils.message("user.not.exist"));
        }
        String newPasswd = new Md5Hash(userInfo.getUserName() + DEFAULT_PASSWORD + userInfo.getSalt()).toHex().toString();
        userInfo.setPassword(newPasswd);
        userInfoMapper.resetPassword(userInfo);
        return userInfo;
    }

    @Override
    public UserInfo edit(@NonNull UserVO userVO) {
        Long roleId = userVO.getRoleId();
        Role role = roleMapper.getById(roleId);
        if (role == null) {
            throw new BusinessException(MessageUtils.message("role.not.exist"));
        }
        Long userId = userVO.getId();
        UserInfo userInfo = userInfoMapper.getById(userId);
        if (userInfo == null) {
            throw new BusinessException(MessageUtils.message("user.not.exist"));
        }
        userInfoMapper.updateUserRole(userId, roleId);
        return userInfo;
    }

    @Override
    public UserInfo modifyPasswd(@NonNull ModifyPasswd modifyPasswd) {
        UserInfo userInfo = ShiroUtils.getSysUser();
        String mdPass = new Md5Hash(userInfo.getUserName() + modifyPasswd.getOriginPass() + userInfo.getSalt()).toHex().toString();
        if (!userInfo.getPassword().equals(mdPass)) {
            throw new BusinessException(MessageUtils.message("user.origin.pass.error"));
        }
        String newPass = modifyPasswd.getNewPass();
        String newPassMd = new Md5Hash(userInfo.getUserName() + newPass + userInfo.getSalt()).toHex();
        userInfo.setPassword(newPassMd);
        userInfoMapper.updatePasswd(userInfo);
        ShiroUtils.setSysUser(userInfo);
        return userInfo;
    }

    @Override
    public UserVO getUserInfoById(Long id) {
        return userInfoMapper.getUserVOById(id);
    }

    private static String getRandomSalt() {
        String model = "abcdefghijklmnopqrstuvwxyz1234567890";
        StringBuffer salt = new StringBuffer();
        char[] m = model.toCharArray();
        for (int i = 0; i < 6; i++) {
            char c = m[(int) (Math.random() * 36)];
            salt = salt.append(c);
        }
        return salt.toString();
    }
}
